package com.cml.dm.admin.service.handler;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cml.dm.admin.entity.DmExeLogger;
import com.cml.dm.admin.entity.DmMetadata;
import com.cml.dm.admin.mapper.DynamicSqlMapper;
import com.cml.dm.admin.service.SqlGenerateServiceFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.Map;
import java.util.Stack;

public class DelDataTaskHandler extends  TaskHandler{

    private SqlGenerateServiceFactory sqlGenerateServiceFactory;

    private DynamicSqlMapper dynamicSqlMapper;

    public DelDataTaskHandler(){
        this.sqlGenerateServiceFactory = SpringUtil.getBean(SqlGenerateServiceFactory.class);
        this.dynamicSqlMapper = SpringUtil.getBean(DynamicSqlMapper.class);
    }

    @Override
    public void execute(DmMetadata dmMetadata, DmExeLogger dmExeLogger, Object extParameter) {
        dmExeLogger.setExeType(3);
        //逆向执行，以适配join删除数据
        DmMetadata curMetadata = this.reverse(dmMetadata);
        do {
            //TODO 获取到原有的id;
            Map<String, JSONObject> dataMap = (Map<String, JSONObject>)extParameter;
            JSONObject nodeData = dataMap.get(curMetadata.getNodeId());
            JSONArray pkIdIndexs = nodeData.getJSONArray("pkIdIndex");
            if(!pkIdIndexs.isEmpty()){
                String pks = StringUtils.join(pkIdIndexs.toArray(),",");

                List<String> sqls = sqlGenerateServiceFactory.getSqlGenerateService(curMetadata,dmExeLogger,extParameter).sqlGenerate(curMetadata,dmExeLogger,pks);
                //TODO 执行sql
                for(String sql : sqls){
                    dynamicSqlMapper.update(sql);
                }
            }

            curMetadata = curMetadata.getNextDmMetadata();
        }while (null != curMetadata);
    }

    private DmMetadata reverse(DmMetadata dmMetadata){
        //重新组合任务链表，逆向执行，以适配有join条件的. 使用Stack存储任务列表
        Stack<DmMetadata> stack = new Stack<>();
        do {
            DmMetadata metadata = new DmMetadata();
            BeanUtils.copyProperties(dmMetadata, metadata);;
            metadata.setNext(null);
            metadata.setNextDmMetadata(null);
            stack.push(metadata);
            dmMetadata = dmMetadata.getNextDmMetadata();
        }while (null != dmMetadata);

        //最后一个任务变成第一执行
        DmMetadata first = stack.pop();
        //重新组合下级
        DmMetadata metadata = first;
        DmMetadata next;
        while (!stack.isEmpty()){
            next = stack.pop();
            metadata.setNext(next.getNodeId());
            metadata.setNextDmMetadata(next);
            metadata = next;
        }
        return first;
    }
}
